package face.pay.api.withdraw.service.impl;

import face.pay.api.withdraw.service.IWithdrawCallbackService;
import face.pay.dao.CashRecodeInfoDao;
import face.pay.dao.InterfaceRequestLogDao;
import face.pay.dao.UserAccountDao;
import face.pay.entity.CashRecodeInfo;
import face.pay.entity.InterfaceRequestLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WithdrawCallbackService implements IWithdrawCallbackService {

    @Autowired
    private CashRecodeInfoDao withdrawOrderDao;


    @Autowired
    private InterfaceRequestLogDao interfaceRequestLogDao;


    @Autowired
    private UserAccountDao userAccountDao;

    /**
     * 提现接口回调
     *
     * @param transData
     * @return
     */
    @Override
    @Transactional
    public String withdrawCallback(Map map_result) {

        CashRecodeInfo record = new CashRecodeInfo();
        //获取返回提现订单号
        Long transId = new Long((String) map_result.get("MerBillNo"));
        record.setId(transId);
        log.info("提现订单id:{}回调结果<<<<<<<:{}", transId, map_result);
        //日志记录回调参数
        createdLog(map_result, transId);
        CashRecodeInfo order = this.withdrawOrderDao.queryOrderInfo(record);
        if (order == null || "00".equals(order.getSucceed()) || "11".equals(order.getSucceed())) {
            //订单已经被处理了
            return "OK";
        } else {
            //订单未被处理
            CashRecodeInfo updataParm = new CashRecodeInfo();
            updataParm.setId(transId);
            updataParm.setSucceed((String) map_result.get("Succeed"));
            updataParm.setMessage((String) map_result.get("Result"));
            this.withdrawOrderDao.update(updataParm);
            if ("11".equals(map_result.get("Succeed"))) {
                //转账退回 退回余额
                HashMap<String, Object> userAccoountParm = new HashMap<>();
                userAccoountParm.put("userId", order.getUserId());
                userAccoountParm.put("money", +order.getAmount());
                this.userAccountDao.update(userAccoountParm);
            }
            return "OK";
        }
    }

    /**
     * 记录回调参数
     *
     * @param map_result
     * @param transId
     */
    private void createdLog(Map map_result, Long transId) {
        InterfaceRequestLog lg = new InterfaceRequestLog();
        lg.setBiz(1);
        lg.setBiz_id(transId);
        lg.setInterface_id(2);
        lg.setIn_param(map_result.toString());
        lg.setOut_param("OK");
        lg.setStatus(1);
        this.interfaceRequestLogDao.insert(lg);
    }
}
